/* eslint-disable react/jsx-indent */
/* eslint-disable no-nested-ternary */
import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { exportQAHistories } from '@/services/download';
import qs from 'qs';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Card,
  Row,
  Col,
  Form,
  Input,
  Button,
  message,
  Drawer,
  Icon,
  Checkbox,
  Table,
  Tag,
  Select,
  Modal,
  Radio,
  Spin,
  Upload,
  Tabs,
} from 'antd';
import Custom from './custom.js';
import CustomNew from './customNew';
import { routerRedux } from 'dva/router';
import BackRouter from '@/pages/CapacityStudy/KnowledgeSmartMaintenance/backRouter';

const { TabPane } = Tabs;
const FormItem = Form.Item;
const Search = Input.Search;
const InputGroup = Input.Group;
import styles from './index.less';
const { Option } = Select;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
import pen from '../../../assets/icons/bi.png';
import ljx from '../../../assets/icons/垃圾箱.png';

class NoEnumerationNew extends Component {
  state = {
    okname: this.props.history.location.params
      ? this.props.history.location.params.id.name
      : decodeURIComponent(window.location.href.split('?')[1].split('&')[1]),
    disabled: true,
    name: this.props.history.location.params
      ? this.props.history.location.params.id.name
      : decodeURIComponent(window.location.href.split('?')[1].split('&')[1]),
    okid: this.props.history.location.params
      ? this.props.history.location.params.id.id
      : decodeURIComponent(window.location.href.split('?')[1].split('&')[0]),
    mockValue: '',
    listday: [],
    dataSource2: [],
    totab: [],
    login: false,
    close: true,
  };

  componentDidMount() {
    // console.log(this.props.history.location.params.id)
    this.fetchb();
  }

  fetchb = () => {
    this.setState({
      login: true,
    });
    const { dispatch, currentUser } = this.props;
    const { okid, page, limit, itemNames } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customDictionary/unEnumList',
        payload: { id: okid, page, limit, itemNames },
        callback: res => {
          console.log('componentWillMount', res);
          let a = res.list;
          a.map((item, index) => {
            item['key'] = index;
          });
          this.setState({
            dataSource2: a,
            listday: a,
            totab: res.total,
            login: false,
          });
        },
      });
    });
  };

  returnButton = () => {
    return <BackRouter style={{ float: 'right' }} pathname="/basic/customDictionary" />;
  };

  returnHome = () => {
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname: '/basic/customDictionary',
      })
    );
  };

  // 新增
  handleSubmitC = () => {
    let arr = this.state.listday;
    let dictItems = {
      word: 'regex',
      synWords: [],
    };
    arr.push(dictItems);
    console.log(arr);
    this.setState({
      listday: arr,
    });
  };

  busChanges = (value, index) => {
    console.log(value, index);
    let arr = this.state.listday;
    arr[index].word = value;
    console.log(this.state.listday);
  };

  //删除
  handleSubmitA = index => {
    console.log(this.state.listday);
    let arr = this.state.listday;
    arr.splice(index, 1);
    console.log(arr);
    this.setState({
      listday: arr,
    });

    console.log(index);
  };

  busChange = (e, index) => {
    console.log(e.target.value, index);
    let arr = this.state.listday;
    arr[index].synWords = [];
    arr[index].synWords.push(e.target.value);
    this.setState({
      listday: arr,
    });
    console.log(this.state.listday);
  };

  handleSubmitB = () => {
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customDictionary/fetchh',
        payload: { dictId: this.state.okid, dictItems: this.state.listday },
        callback: res => {
          console.log('componentWillMount', res);
          if (res.status === true) {
            message['success'](`${res.msg}`);
          }
          if (res.status === false) {
            message['error'](`${res.msg}`);
          }
          // this.fetch()
          this.fetchb();
        },
      });
    });
  };

  // 词典名称修改
  textInput = () => {
    const { getFieldDecorator } = this.props.form;
    return (
      <div className={styles.flexcen}>
        <Form layout="inline" onSubmit={this.handleSubmit}>
          <FormItem label="实体名称">
            {getFieldDecorator('namecid', {
              initialValue: '',
            })(
              <div>
                <Input
                  defaultValue={this.state.name}
                  disabled={this.state.disabled}
                  onPressEnter={this.saveChanges}
                  onChange={this.namegai}
                />
              </div>
            )}
          </FormItem>
          {this.state.disabled === true ? (
            <span>
              <Icon onClick={this.modifyClick} className={styles.fleximg} type="edit" />
            </span>
          ) : (
            <span>
              <Icon onClick={this.bcClick} className={styles.fleximg} type="check" />
            </span>
          )}
        </Form>
      </div>
    );
  };

  namegai = e => {
    console.log(e.target.value);
    this.setState({ mockValue: e.target.value });
  };

  // 字典名称显示或隐藏
  modifyClick = () => {
    this.setState({
      disabled: false,
    });
  };

  bcClick = () => {
    if (this.state.mockValue === '') {
      // message['warning']('未修改')

      this.setState({
        disabled: true,
      });
      console.log(this.state.okid);
      const { dispatch } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'customDictionary/fetche',
          payload: { dictId: this.state.okid, dictName: this.state.okname },
          callback: res => {
            console.log('componentWillMount', res);
            if (res.status === true) {
              message['success'](`${res.msg}`);
            }
          },
        });
      });
    } else {
      this.setState({
        disabled: true,
      });
      // message['success']('修改成功')
      // 可枚举页 修改词典
      console.log(this.state.okid);
      const { dispatch } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'customDictionary/fetche',
          payload: { dictId: this.state.okid, dictName: this.state.mockValue },
          callback: res => {
            console.log('componentWillMount', res);
            if (res.status === true) {
              message['success'](`${res.msg}`);
            }
            if (res.status === false) {
              message['error'](`${res.msg}`);
            }
          },
        });
      });
    }
  };

  onClose = () => {
    this.setState({
      close: false,
    });
    setTimeout(()=>{
      const {dispatch} = this.props
      dispatch(routerRedux.push({
        pathname:'/basic/customDictionary'
      }));
    },300)
  }

  // eslint-disable-next-line react/sort-comp
  render() {
    return (
      <Drawer
        className="zdyset"
        title={
          <span  onClick={this.onClose} style={{cursor:'pointer'}}>
             <Icon type="arrow-left" style={{ marginRight: 20 }} />
            不可枚举实体
          </span>
        }
        placement="right"
        closable={false}
        onClose={this.onClose}
        visible={this.state.close}
        width="calc(100vw - 245px)"
        destroyOnClose
      >
        <div>
          <div className={styles.backgroundp}>
            {/* {this.textInput()} */}
            <Spin spinning={this.state.login}>
              <Button
                style={{ marginBottom: 18 }}
                type="primary"
                onClick={this.handleSubmitC}
                icon="plus"
              >
                <FormattedMessage id="app.customDictionary.add-new-format" defaultMessage="Rank" />
              </Button>
              {this.state.listday.map((item, index) => {
                return (
                  <Spin spinning={this.state.login}>
                    <Form layout="inline" style={{ marginBottom: 10 }}>
                      <FormItem>
                        <Select
                          style={{ width: 160 }}
                          defaultValue={item.word === '' ? 'regex' : item.word}
                          onChange={e => this.busChanges(e, index)}
                        >
                          <Option value="regex">
                            <FormattedMessage
                              id="app.customDictionary.regular-expression"
                              defaultMessage="Regular expression"
                            />
                          </Option>
                          <Option value="placeholder">
                            <FormattedMessage
                              id="app.customDictionary.placeholder"
                              defaultMessage="placeholder"
                            />
                          </Option>
                        </Select>
                      </FormItem>
                      <FormItem>
                        <Input
                          style={{ width: 354 }}
                          value={item.synWords[0]}
                          onChange={e => this.busChange(e, index)}
                        />
                      </FormItem>
                      <FormItem>
                        <span>
                          <img src={ljx} onClick={() => this.handleSubmitA(index)} />
                        </span>
                      </FormItem>
                    </Form>
                  </Spin>
                );
              })}
              <div>
                <Button
                  style={{ background: '#19c3f3', color: '#ffffff', marginTop: 18 }}
                  onClick={this.handleSubmitB}
                >
                  保存
                </Button>
              </div>
              <div className={styles.textOne}>
                <div style={{ padding: '20px 30px 40px 30px' }}>
                  <h5 style={{ fontWeight: 'bold' }}>
                    <FormattedMessage id="app.customDictionary.enumeration-texta" />
                  </h5>
                  <p>
                    <FormattedMessage id="app.customDictionary.enumeration-textb" />
                  </p>
                  <p>
                    <FormattedMessage id="app.customDictionary.enumeration-textc" />
                  </p>
                  <p>可用 ？代表单个数字/字母，* 代表任意多个(>=1)数字/字母</p>
                  <h5 style={{ fontWeight: 'bold' }}>
                    <FormattedMessage id="app.customDictionary.enumeration-textd" />
                  </h5>
                  <p>按照标准的正则表达式语法编写即可，具体语法可参考：正则表达式介绍</p>
                  <p style={{ lineHeight: 2 }}>
                    <span style={{ fontWeight: 700 }}>注:</span>
                    此处的正则表达式不支持使用大写字母。(因为对于用户输入的内容，系统会先将其中的大写字母都转换成小写，然后再进行识别抽取，因此如果用大写字母的话会造成系统无法识别。)
                  </p>
                </div>
              </div>
            </Spin>
          </div>
        </div>
      </Drawer>
    );
  }
}

export default connect(({ user }) => ({
  // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(NoEnumerationNew));
